package com.school.movie.business.web.controller;

import com.school.movie.business.web.model.vo.AgentInfo;
import com.school.movie.business.web.model.vo.Manager;
import com.school.movie.business.web.model.vo.ProvinceVo;
import com.school.movie.common.bean.PageBean;
import com.school.movie.common.utils.*;
import com.school.movie.service.imp.ManagerServiceImp;
import com.school.movie.service.imp.SysLogServiceImp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @author zhaoren
 */
@Controller
@Slf4j
public class LoginController {

    @Autowired
    ManagerServiceImp managerService;
    @Autowired
    SysLogServiceImp logService;
    @Value("${upload.absPath}")
    String absPath;

    /**
     * 用户登录
     *
     * @param manager
     * @param randCode
     * @param request
     * @param session
     * @param map
     * @return
     */
    @RequestMapping("/login")
    public String login(Manager manager
            , String randCode
            , HttpServletRequest request
            , HttpSession session
            , ModelMap map
    ) {
        if (session.getAttribute("rand") == null) {
            return "login";
        }
        String msg = "";
        String rand = session.getAttribute("rand").toString();
        if (rand == null || randCode == null) {
            msg = "验证码错误";
            map.addAttribute("msg", msg);
            return "login";
        }
        rand = rand.toUpperCase();
        randCode = randCode.toUpperCase();
        if (!rand.equals(randCode)) {
            msg = "验证码错误";
            map.addAttribute("msg", msg);
            return "login";
        }
        manager.setManagerPassword(AesUtils.encryptStr(manager.getManagerPassword(), AesUtils.SECRET_KEY));

        Manager mgr = managerService.login(manager);

        if (mgr == null) {
            msg = "用户名或密码错误,或者账户被禁用";
            map.addAttribute("msg", msg);
            return "login";
        }
        if (mgr.getAgent().getInvalid() == 0) {
            msg = "该影院用户禁止登陆";
            map.addAttribute("msg", msg);
            return "login";
        }
        session.setAttribute("userinfo", mgr);
        logService.add(BaseConstants.LOG_LOGIN, "管理员编号=" + mgr.getManagerId() + ";管理员名称:" + mgr.getManagerName());
        log.info("login...........");
        //重定向到主页面，以免刷新重复提交表单
        return "redirect:main";
    }

    @RequestMapping("/updateInfo")
    public String updateInfo(Manager manager, HttpSession session, ModelMap map) {
        managerService.updateInfo(manager);
        manager = managerService.getById(manager.getManagerId());
        session.setAttribute("userinfo", manager);
        map.addAttribute("manager", manager);
        return "mySet";
    }

    @RequestMapping("/updatePwd")
    public String updatePwd(Manager manager, ModelMap map) {
        String pwd = AesUtils.encryptStr(manager.getOldpwd(), AesUtils.SECRET_KEY);
        Manager mgr = managerService.getById(manager.getManagerId());
        String msg = "";
        if (mgr.getManagerPassword().equals(pwd)) {
            manager.setManagerPassword(AesUtils.encryptStr(manager.getManagerPassword(), AesUtils.SECRET_KEY));
            managerService.updatePwd(manager);
            msg = "pwdsucc";
        } else {
            msg = "pwderror";
        }
        map.addAttribute("msg", msg);
        return "mySet";
    }

    @RequestMapping("/list")
    public String list(AgentInfo agent, PageBean pager, HttpSession session, ModelMap map) {
        if (agent == null || agent.getMobile() == null) {
            if (session.getAttribute("agent") != null) {
                agent = (AgentInfo) session.getAttribute("agent");
            }
        } else {
            session.setAttribute("agent", agent);
        }
        List<ProvinceVo> provList = managerService.provinceList();

        //0=影院管理员；3=系统管理员
        if (ContextUtils.getManagerInfo().getManagerType() != 3) {
            agent.setAgentId(ContextUtils.getManagerInfo().getAgentId());
        }

        int cnt = managerService.count(agent);
        pager.setTotalRows(cnt);
        List<Manager> mgrList = managerService.mgrList(agent, pager);

        pager.setData(mgrList);
        map.addAttribute("pager", pager);
        map.addAttribute("provList", provList);
        map.addAttribute("agent", agent);
        return "manager";
    }

    @RequestMapping("/del")
    public String del(String ids, PageBean pager, HttpSession session, ModelMap map) {
        String arr[] = ids.split(",");
        managerService.del(arr);
        logService.add(BaseConstants.LOG_DEL, "管理员编号=" + ContextUtils.getManagerInfo().getManagerId() + ";管理员名称:" + ContextUtils.getManagerInfo().getManagerName() + ",删除了编号为" + ids + "的用户");
        AgentInfo agent = (AgentInfo) session.getAttribute("agent");
        if (agent == null) {
            agent = new AgentInfo();
        }
        List<ProvinceVo> provList = managerService.provinceList();
        int cnt = managerService.count(agent);
        pager.setTotalRows(cnt);
        List<Manager> mgrList = managerService.mgrList(agent, pager);
        pager.setData(mgrList);
        map.addAttribute("pager", pager);
        map.addAttribute("provList", provList);
        map.addAttribute("agent", agent);
        return "manager";
    }

    @RequestMapping("/update")
    public String update(int managerId, ModelMap map) {
        Manager mgr = managerService.getById(managerId);
        List<JsonData> mtList = new ArrayList<>();
        if (ContextUtils.getManagerInfo().getManagerType() == 3) {
            mtList.add(new JsonData("0", "影院管理员"));
            mtList.add(new JsonData("3", "系统管理员"));
        } else if (ContextUtils.getManagerInfo().getManagerType() == 0) {
            mtList.add(new JsonData("0", "影院管理员"));
        }

        int agentId = 0;
        if (ContextUtils.getManagerInfo().getManagerType() != 3) {
            agentId = ContextUtils.getManagerInfo().getAgent().getAgentId();
        }
        List<AgentInfo> agentList = managerService.agentList(agentId);

        map.addAttribute("manager", mgr);
        map.addAttribute("agentList", agentList);
        map.addAttribute("mtList", mtList);
        return "managerAdd";
    }

    @RequestMapping("/init")
    public String init(ModelMap map) {
        List<JsonData> mtList = new ArrayList<>();
        if (ContextUtils.getManagerInfo().getManagerType() == 3) {
            mtList.add(new JsonData("0", "影院管理员"));
            mtList.add(new JsonData("3", "系统管理员"));
        } else if (ContextUtils.getManagerInfo().getManagerType() == 0) {
            mtList.add(new JsonData("0", "影院管理员"));
        }
        int agentId = 0;
        if (ContextUtils.getManagerInfo().getManagerType() != 3) {
            agentId = ContextUtils.getManagerInfo().getAgent().getAgentId();
        }
        List<AgentInfo> agentList = managerService.agentList(agentId);
        map.addAttribute("agentList", agentList);
        map.addAttribute("mtList", mtList);
        return "managerAdd";
    }

    @RequestMapping("/save")
    public String save(Manager manager, @RequestParam(value = "file") MultipartFile file, ModelMap map) throws IOException {
        Manager mgr;
        if (Objects.nonNull(file) && Objects.nonNull(file.getOriginalFilename())){
            String imageName = UUID.randomUUID().toString() + MediaUtil.getExtendName(file);
            file.transferTo(new File(absPath + imageName));
            manager.setHeadimg("card/" + imageName);
        }

        if (manager.getManagerId() > 0) {
            if ("".equals(manager.getManagerPassword())) {
                mgr = managerService.getById(manager.getManagerId());
                manager.setManagerPassword(mgr.getManagerPassword());

            } else {
                manager.setManagerPassword(AesUtils.encryptStr(manager.getManagerPassword(), AesUtils.SECRET_KEY));
            }
            managerService.update(manager);
            logService.add(BaseConstants.LOG_UPDATE, manager.toString());
        } else {
            //加密处理
            manager.setManagerPassword(AesUtils.encryptStr(manager.getManagerPassword(), AesUtils.SECRET_KEY));
            managerService.add(manager);
            logService.add(BaseConstants.LOG_ADD, manager.toString());
        }
        AgentInfo agent = new AgentInfo();
        List<ProvinceVo> provList = managerService.provinceList();
        int cnt = managerService.count(agent);
        PageBean pager = new PageBean();
        pager.setTotalRows(cnt);
        List<Manager> mgrList = managerService.mgrList(agent, pager);
        pager.setData(mgrList);
        map.addAttribute("pager", pager);
        map.addAttribute("provList", provList);
        map.addAttribute("agent", agent);
        return "manager";
    }
}
